package service;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.EntityMode;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import dao.hb.NImage;
import dao.hb.PinDataset;
import dao.hb.UUser;
import net.bat.db.BaseDAOImpl;
import net.bat.pt.BObj;
import net.bat.service.HDUtil;
import net.bat.service.IHandle;
import net.bat.service.cb.HHUtil;
import net.cs.um.UMService;

public class ZpService implements IHandle {
	public static final String EN_DATASET = "dao.hb.PinDataset";
	public static final String EN_DATASET_PERSON = "dao.hb.PinDatasetPerson";
	public static final String HQL_DATASET_COUT = "from "+ EN_DATASET_PERSON+" where datasetId=?";
    public static final char METHOD_CREATE_DATASET='N';   
    public static final char METHOD_APPEND_DATASET='A';  
    public static final char METHOD_REMOVE_DATASET='R';  
    
	private Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").setPrettyPrinting().create();
    
	/**
	 * @return the dao
	 */
	public BaseDAOImpl getDao() {
		return dao;
	}
	/**
	 * @param dao the dao to set
	 */
	public void setDao(BaseDAOImpl dao) {
		this.dao = dao;
	}

	@Autowired
	private BaseDAOImpl dao;

	/**
	 * 获得检索结果数目
	 * @param filter
	 * @return
	 */
	public int getCountOper(String filter){
		return 0;
	}
/**
 * 获得实际加入目标数据集的数目
 * @param filter
 * @param dataset
 * @return
 */
	public int getCountOper(String filter, int dataset){
		return 0;
	}
/**
 * 	根据检索结果删除从数据集条目
 * @param filter
 * @return
 * @throws Exception 
 */
	public int RemoveDataset(HashMap<String, Object> rm,HttpServletRequest request) throws Exception{
		String hql = (String)rm.get("hql");
		Object ds_id = rm.get("ds_id");
		int pos1 = hql.indexOf("(");
		int pos2 = hql.lastIndexOf(")");
		String filter_b="";
		if(pos1!=-1 && pos2!=-1){
			filter_b=" where "+hql.substring(pos1,pos2+1);
		}
		String dhql ="delete from PinDatasetPerson A where  A.datasetId="
	    		+ds_id
	    		+" and   A.personId in (select B.id from PinPerson B  "
	    		+filter_b
	    		+")";
		PinDataset po = (PinDataset)dao.loadPO(EN_DATASET, ds_id.toString());
		Integer total_old = po.getTotal();

		UUser usr = UMService.getUserBySession(request);
		int total = dao.updateByQuery(dhql,null);
		int total_new = dao.getCountByQuery(HQL_DATASET_COUT, new Object[]{po.getId()});
		Object[] remark1= new Object[]{"total",total_old,total_new};
		Object[] remarks = new Object[]{remark1};
		String remark_str =gson.toJson(remarks);
		po.setTotal(total_new);
		po.setDtModify(new Date());
		dao.update(po);
		HDUtil.dblog(dao, usr.getId(), EN_DATASET, po.getId().toString(), BObj.ACTION_UPDATE, remark_str);
		return total;
	}
/**
 * 将检索结果添加到数据集	
 * @param filter
 * @return
 * @throws Exception 
 */
	public Object[] appendDataset(HashMap<String, Object> rm,HttpServletRequest request) throws Exception{
	    //dao.updateByQuery("insert into PinDatasetPerson (datasetId, personId) select 2,id from PinPerson  where id <10",null);
		Object[] rt = new Object[4];
		String type=(String)rm.get("type");
		boolean b_share = type.equals("共享");
		int total= (Integer)rm.get("total");
		rt[0]=total;
		String filter = (String)rm.get("filter");
		if(filter==null){
			Integer[] sids = (Integer[])rm.get("sids");
			StringBuffer sbuf = new StringBuffer("(");
			for(int i=0; i<sids.length; i++){
				if(i==0){
					sbuf.append(sids[i]);
				}
				else sbuf.append(","+sids[i]);
			}
			sbuf.append(")");
			filter = b_share?(" from PinPerson B where B.id in "+sbuf.toString()): (" from PinPerson where id in "+sbuf.toString());
		}
		
		Object ds_id = rm.get("ds_exist");
		UUser usr = UMService.getUserBySession(request);
		//新建数据集
		if(ds_id==null || ds_id.toString().equals("")){
			String ds_new= (String)rm.get("ds_new");
			ClassMetadata cm=dao.getClassMeta(EN_DATASET);	
			PinDataset po= (PinDataset)cm.instantiate(null,EntityMode.POJO);
			po.setDatasetname(ds_new);
			po.setTotal(total);
			po.setDtCreate(new Date());
			po.setDtModify(new Date());
			po.setUsername(usr.getUserId());
			dao.save(po);
			ds_id = po.getId();
			rt[2]=ds_id;
			rt[3]=ds_new;
			
			String hql = "insert into PinDatasetPerson ( datasetId, personId) select "+ds_id+" "
					+(b_share?",B.id ":",id ")
					+filter;
			total = dao.updateByQuery(hql,null);
			rt[1]=total;
			HDUtil.dblog(dao, usr.getId(), EN_DATASET, po.getId().toString(), BObj.ACTION_ADD, null);
			return rt;
		}else{
			if(b_share){
				if(filter.indexOf("where")==-1){
					filter +="  where B.id not in (select personId from PinDatasetPerson where datasetId="+ds_id+")";
				}else{
					filter +="  and B.id not in (select personId from PinDatasetPerson where datasetId="+ds_id+")";
				}
			}else{
				if(filter.indexOf("where")==-1){
					filter +="  where id not in (select personId from PinDatasetPerson where datasetId="+ds_id+")";
				}else{
					filter +="  and id not in (select personId from PinDatasetPerson where datasetId="+ds_id+")";
				}
			}
			
				String hql = "insert into PinDatasetPerson (datasetId, personId) select "+ds_id+ (b_share?",B.id ":",id ")+filter;						
				total =dao.updateByQuery(hql,null);
				PinDataset po = (PinDataset)dao.loadPO(EN_DATASET, ds_id.toString());
				Integer total_old = po.getTotal();
				int total_new = dao.getCountByQuery(HQL_DATASET_COUT, new Object[]{po.getId()});
				Object[] remark1= new Object[]{"total",total_old,total_new};
				Object[] remarks = new Object[]{remark1};
				String remark_str =gson.toJson(remarks);

				HDUtil.dblog(dao, usr.getId(), EN_DATASET, po.getId().toString(), BObj.ACTION_UPDATE, remark_str);
				po.setDtModify(new Date());
				po.setTotal(total_new);
				dao.update(po);
			rt[1]=total;
			rt[2]=ds_id;
			rt[3]=po.getDatasetname();
			return rt;
		}
	}
	
	@Override
	public Object handle(char method, HashMap<String, Object> rm,
			HttpServletRequest request) throws Exception {
		// TODO Auto-generated method stub
		switch(method){
		case METHOD_APPEND_DATASET:
			return appendDataset(rm,request);
		case METHOD_REMOVE_DATASET:
			return RemoveDataset(rm,request);
		}
		return null;
	}
}
